from django.shortcuts import render
from django.views import View
from django import http
import json

from utils.mixin import LoginRequiredJsonMixin
from homes.models import House
from orders.models import Order
from utils.errmsg_info import error_no, error_msg

# Create your views here.


class HouseOrderView(LoginRequiredJsonMixin, View):
    """
    /api/v1.0/orders?role=landlord
    /api/v1.0/orders?role=custom
    """
    def post(self, request):
        # 提取参数
        json_dict = json.loads(request.body.decode())
        house_id = json_dict.get('house_id')
        start_date = json_dict.get('start_date')
        end_date = json_dict.get('end_date')

        # 自己提取的参数(做实验用)
        price = json_dict.get('house_price')
        days = end_date - start_date
        amount = price * days
        house = House.objects.get(id=house_id)
        if house.user != request.user:
            # 被预定的日期还没判断
            order = Order.objects.create(
                user=request.user,
                house_id=house_id,
                begin_date=start_date,
                end_date=end_date,
                days=days,
                house_price=price,
                amount=amount,
                status=Order.ORDER_STATUS_ENUM.get(2)
            )

            return http.JsonResponse({
                'data': {'order_id': order.id},
                'errno': error_no['OK'],
                'errmsg': '下单成功'
            })


